﻿using GamFi.API.Application.Contracts.Chains.GetChainById;
using GamFi.API.Application.Exceptions;
using GamFi.API.Application.Interfaces;
using GamFi.API.Application.Resources;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace GamFi.API.Application.Features.Queries.Chain.GetChainById;

public class GetChainByIdQueryHandler(IDbContext dbContext, IStringLocalizer<ExceptionMessages> localizer) : IRequestHandler<GetChainByIdQuery, GetChainByIdResponse>
{
    public async Task<GetChainByIdResponse> Handle(GetChainByIdQuery request, CancellationToken cancellationToken)
    {
        if (request is null)
            throw new RequestException(localizer[nameof(RequestException.RequestIsEmpty)]);
        
        var chain = await dbContext.Chains.FirstOrDefaultAsync(c => c.Id == request.ChainId, cancellationToken);

        if (chain is null)
            return new GetChainByIdResponse { IsFound = false };

        return new GetChainByIdResponse
        {
            IsFound = true,
            Id = chain.Id,
            Name = chain.Name,
            ImageId = chain.ImageId
        };
    }
}